﻿using Microsoft.Extensions.Hosting;
using FreeRedis;
using Masuit.Tools.Security;
using Microsoft.Extensions.Logging;
using Masuit.Tools;

namespace sixgod.Common.RSA
{
    public class RsaHostedService:BackgroundService
    {
        private readonly ILogger _logger;
        private readonly RedisClient _redisClient;
        private Timer _timer;
        /// <summary>Initializes a new instance of the <see cref="T:System.Object" /> class.</summary>
        public RsaHostedService(ILogger<RsaHostedService> logger, RedisClient redisClient)
        {
            _logger = logger;
            _redisClient = redisClient;
        }

        private void Execute(object state)
        {
            try
            {
                CreateRSA();
            }
            catch (System.Exception e)
            {
                _logger.LogError(e,"生成rsa出差");
            }
            
        }

        private void CreateRSA()
        {
            Random rnd = new Random();
            int num = rnd.StrictNext(2048);

            var rsa = RsaCrypt.GenerateRsaKeys(RsaKeyType.PKCS1);
            _redisClient.HMSet(CacheKeyConsts.LOGIN_KEY, CacheKeyConsts.LOGIN_PRIVATE_KEY, rsa.PrivateKey);
            _redisClient.HMSet(CacheKeyConsts.LOGIN_KEY, CacheKeyConsts.LOGIN_PUBLIC_KEY, rsa.PublicKey);
        }

        private void ConfigService()
        {
            var t = new Timer(Execute);
            t.Change(0,1000*30);
        }

        /// <summary>
        /// This method is called when the <see cref="T:Microsoft.Extensions.Hosting.IHostedService" /> starts. The implementation should return a task that represents
        /// the lifetime of the long running operation(s) being performed.
        /// </summary>
        /// <param name="stoppingToken">Triggered when <see cref="M:Microsoft.Extensions.Hosting.IHostedService.StopAsync(System.Threading.CancellationToken)" /> is called.</param>
        /// <returns>A <see cref="T:System.Threading.Tasks.Task" /> that represents the long running operations.</returns>
        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            if (stoppingToken.IsCancellationRequested == false)
            {
                await Task.Run(ConfigService);
            }
        }

    }
}
